# -*- coding:utf-8 -*-
import os
import numpy as np
import cv2
from scipy import misc
import detect_face
import tensorflow as tf
REPO_DIRNAME = os.path.dirname(os.path.abspath(__file__))
MODEL_DIRNAME = os.path.join(REPO_DIRNAME, 'models')
UPLOAD_FOLDER = '/home/dl/test/face/uploadimages'


mtcnn_model_dir = '{}/models/mtcnn'.format(REPO_DIRNAME)
gpu_memory_fraction = 0.25
minsize = 20 #minimum size of face
threshold = [0.6, 0.7, 0.7]  # three steps's threshold
factor = 0.709  # scale factor

with tf.Graph().as_default():
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
    with sess.as_default():
        pnet, rnet, onet = detect_face.create_mtcnn(sess, mtcnn_model_dir)

def detect(image):
    bounding_boxes, points = detect_face.detect_face(image, minsize,pnet, rnet,
                                                onet, threshold, factor)
    nrof_faces = bounding_boxes.shape[0]
    print('detect face :{}').format(nrof_faces)
    scaled_faces = []
    if nrof_faces > 0:
        for face_position in bounding_boxes:
            face_position = face_position.astype(int)
            cv2.rectangle(image, (face_position[0], face_position[1]), (face_position[2], face_position[3]),
                          (0, 255, 0), 2)
    cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
    cv2.imshow('image',image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    sess.close()

def main():
    image = cv2.imread('/home/dl/share/No.2_20170901163018.JPG')
    detect(image)

if __name__ == '__main__':
    main()